<?

class Smutty_Smut {

	/**
	 *  constructor
	 *
	 */

	function Smutty_Smut() {
		Smutty_Main::loadRequiredClasses();
	}

	/**
	 *  prints out a usage message for smut
	 *
	 */

	function usage() {
		$tpl = new Smutty_Template_Smutty();
		$tpl->display( 'smut/usage.tpl' );
		exit();
	}

	/**
	 *  creates a controller
	 *
	 *  @param [name] the name of the controller
	 *
	 */

	function createController( $name ) {
		// write the controller file
		$tpl = new Smutty_Template_Smutty();
		$tpl->assign( 'name', $name );
		$this->writeFile(
			'application/controllers/' . $name . 'Controller.php',
			$tpl->fetch('smut/controller.tpl')
		);
		// make sure views folder exists
		mkdir( 'application/views/' . strtolower($name) );
	}

	/**
	 *  creates a model
	 *
	 *  @param [name] the name of the model to create
	 *
	 */

	function createModel( $name ) {
		$tpl = new Smutty_Template_Smutty();
		$tpl->assign( 'name', $name );
		$this->writeFile(
			'application/models/' . $name . '.php',
			$tpl->fetch('smut/model.tpl')
		);
	}

	/**
	 *  writes the given data to the specified file
	 *
	 *  @param [path] the path of the file
	 *  @param [data] the data to write
	 *
	 */

	function writeFile( $path, $data ) {
		$f = fopen( $path, 'w' );
		fputs( $f, $data );
		fclose( $f );
	}

	/**
	 *  runs a single test case
	 *
	 *  @param [name] the name of the test
	 *
	 */

	function runTest( $name ) {

		include_once 'library/simpletest/unit_tester.php';
		include_once 'library/simpletest/reporter.php';

		Smutty_Main::loadClass(
			'Smutty_Test', 'Smutty_Test_Suite'
		);

		$dir = substr($name,0,6) == 'Smutty' ? 'library' : 'application';
		$path = "$dir/tests/$name.php";

		if ( file_exists($path) ) {
			include_once $path;
			if ( class_exists($name) ) {
				$test = new $name();
				$test->run( new TextReporter() );
			}
		}

		else new Smutty_Exception( "test not found: $path", 'SmuttyTesting' );

	}

	/**
	 *  this is the main entry point for running this
	 *  class from the command line
	 *
	 *  @param [argv] the command line arguments
	 *
	 */

	function run( $argv ) {

		$action = $argv[ 1 ];
		$name = $argv[ 2 ];

		switch ( $action ) {
			case 'controller':
				if ( !$name ) $this->usage();
				$this->createController( $name );
				break;
			case 'model':
				if ( !$name ) $this->usage();
				$this->createModel( $name );
				break;
			case 'test':
				$this->runTest( $name );
				break;
			default:
				$this->usage();
		}

	}

}

?>